import { getUserInfo, login, getMoreInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
const state = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
  },
  // 获取用户信息
  getUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}
const actions = {
  // 登录
  async login(context, data) {
    const token = await login(data)
    setToken(token)
    context.commit('setToken', token)
  },
  // 获得用户信息
  async getUserInfo(context) {
    const res = await getUserInfo()
    const moreRes = await getMoreInfo({ id: res.userId })
    context.commit('getUserInfo', { ...res, ...moreRes })
  },
  // 退出登录,删除对应信息
  loginOut(context) {
    // 删除token
    removeToken()
    // 删除仓库token
    context.commit('setToken', undefined)
    // 清空仓库用户信息
    context.commit('getUserInfo', {})
    // 清空路由
    resetRouter()
    // 修改权限模块的route
    context.commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  mutations,
  state,
  actions
}
